use axum::{Json, extract::{Path, Query}};
use futures_util::TryStreamExt;
use mongodb::{options::GridFsBucketOptions, bson::doc };
use serde_json::{Value, json};

use crate::{code, mdb, query };

pub async fn index(Path( name ): Path<String>, Query(param): Query<Value>) -> Result<Json<Value>, Json<Value>>{
    let conn = mdb::connect().await?;
    let options = GridFsBucketOptions::builder().bucket_name(name).build();
    let bucket = conn.gridfs_bucket(options);

    let doc = if let Some(f) = query::str_op(&param, "id")? {
        doc!{ "_id": mdb::to_object_id(f) }
    }else{
        doc! {}
    };

    match bucket.find(doc).sort(doc! {"uploadDate":-1}).await {
        Ok(mut f) => {
            match f.advance().await {
                Ok(b) => {
                    if b {
                        match f.try_collect::<Vec<_>>().await {
                            Ok(r) => code::data(json!(r)),
                            Err(e) => code::sys(e.to_string())
                        }
                    }else {
                        code::data(json!([]))
                    }
                },
                Err(e) => code::sys(e.to_string())
            }
        },
        Err(e) => code::sys(e.to_string())
    }
}